package com.ruoyi.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.RecordType;
import com.ruoyi.system.mapper.RecordPropMapper;
import com.ruoyi.system.mapper.RecordTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.RecordTableMapper;
import com.ruoyi.system.domain.RecordTable;
import com.ruoyi.system.service.IRecordTableService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 业务表管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-03
 */
@Service
public class RecordTableServiceImpl implements IRecordTableService {
    @Autowired
    private RecordTableMapper recordTableMapper;
    @Autowired
    private RecordTypeMapper recordTypeMapper;

    /**
     * 查询业务表管理
     *
     * @param id 业务表管理主键
     * @return 业务表管理
     */
    @Override
    public RecordTable selectRecordTableById(Long id) {
        return recordTableMapper.selectRecordTableById(id);
    }

    /**
     * 查询业务表管理列表
     *
     * @param recordTable 业务表管理
     * @return 业务表管理
     */
    @Override
    public List<RecordTable> selectRecordTableList(RecordTable recordTable) {
        return recordTableMapper.selectRecordTableList(recordTable);
    }

    /**
     * 新增业务表管理
     *
     * @param recordTable 业务表管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRecordTable(RecordTable recordTable) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            Map<String, Object> map = new HashMap<String,Object>();
            String comment = recordTable.getTbDesc();
            String tbName = recordTable.getTbName();
            map.put("comment", comment);
            map.put("tbName", "`" + tbName + "`");
            String tbType = recordTable.getTbType();
            // 查询该档案分类是否存在同种表类型
            RecordTable recordTb = new RecordTable();
            recordTb.setTypeId(recordTable.getTypeId());
            List<RecordTable> recordTableList = recordTableMapper.selectRecordTableList(recordTb);
            if("1".equals(tbType)){// 案卷管理表
                // 验证表类型：该档案下，没建过任何表
                if(recordTableList.size() != 0){
                    throw new ServiceException("请确保该档案下，未建过任何表！");
                }
                // 创建表
                recordTableMapper.createArchTable(map);
                // 修改档案分类状态为已建表

            }else if("2".equals(tbType)){// 卷内管理表
                // 验证表类型：该档案下，建且只建过案卷表
                if(recordTableList.size() != 1 || !"1".equals(recordTableList.get(0).getTbType())){
                    throw new ServiceException("请确保该档案下，建且只建过案卷表！");
                }
                // 创建表
                recordTableMapper.createFileTable(map);
                // 修改档案分类状态为：已建表
                RecordType recordType = new RecordType();
                recordType.setTypeId(recordTable.getTypeId());
                recordType.setIsCreateTb("1");
                recordTypeMapper.updateRecordType(recordType);
            }else if("3".equals(tbType)){// 独立文件管理表
                // 验证表类型：该档案下，没建过任何表
                if(recordTableList.size() != 0){
                    throw new ServiceException("请确保该档案下，未建过任何表！");
                }
                // 创建表
                recordTableMapper.createFileATable(map);
                // 修改档案分类状态为：已建表
                RecordType recordType = new RecordType();
                recordType.setTypeId(recordTable.getTypeId());
                recordType.setIsCreateTb("1");
                recordTypeMapper.updateRecordType(recordType);
            }else {
                throw new ServiceException("表类型有误，请核实！");
            }
            // 建表成功，插入数据
            recordTable.setCreateBy(SecurityUtils.getUsername());
            recordTable.setUserId(SecurityUtils.getUserId());
            recordTable.setCreateTime(DateUtils.getNowDate());
            recordTableMapper.insertRecordTable(recordTable);
        } catch (ServiceException e) {
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            e.printStackTrace();
            throw new ServiceException("错误信息：" + e);
        }
        return 1;
    }

    /**
     * 修改业务表管理
     *
     * @param recordTable 业务表管理
     * @return 结果
     */
    @Override
    public int updateRecordTable(RecordTable recordTable) {
        recordTable.setUpdateBy(SecurityUtils.getUsername());
        recordTable.setUpdateTime(DateUtils.getNowDate());
        return recordTableMapper.updateRecordTable(recordTable);
    }

    /**
     * 批量删除业务表管理
     *
     * @param ids 需要删除的业务表管理主键
     * @return 结果
     */
    @Override
    public int deleteRecordTableByIds(Long[] ids) {
        return recordTableMapper.deleteRecordTableByIds(ids);
    }

    /**
     * 删除业务表管理信息
     *
     * @param id 业务表管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRecordTableById(Long id) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        int res = 0;
        RecordTable recordTable = recordTableMapper.selectRecordTableById(id);
        try {
            // 保证案卷，卷内都为空
            int i  = recordTableMapper.getCountTable(recordTable.getTbName());
            int j  = recordTableMapper.getCountProp(recordTable.getId());
            if(i > 0){
                throw new GlobalException("record_table表非空，禁止删除");
            }else if(j > 0){
                throw new GlobalException("record_prop表有相关数据，禁止删除");
            }else {
                // 删除数据库表
                recordTableMapper.deleteTable(recordTable.getTbName());
                // 删除表管理记录
                res =  recordTableMapper.deleteRecordTableById(id);
                // 更新档案分类建表状态
                RecordType recordType = new RecordType();
                recordType.setTypeId(recordTable.getTypeId());
                recordType.setIsCreateTb("0");
                recordTypeMapper.updateRecordType(recordType);
            }
        } catch (ServiceException e) {
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            e.printStackTrace();
        }
        return res;
    }
}
